package com.atguigu.gmall.product.controller;

import com.atguigu.gmall.common.result.Result;
import org.apache.commons.io.FilenameUtils;
import org.csource.fastdfs.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @Author: 李旭
 * @Time: 15:35
 * @Description:
 */
@RestController
@RequestMapping("/admin/product")
public class FileUploadController {


    @Value("${image.url}")
    private String imageUrl;
    //上传图片
    @PostMapping("/fileUpload")
    public Result  fileUpload(MultipartFile file){
        try {
            String path = ClassUtils.getDefaultClassLoader().
                    getResource("fdfs_client.conf").getPath();
            //0:配置跟踪器的ip:port
            ClientGlobal.init(path);
            //1:创建TrackerClient 客户端   192.168.200.136:22122
            TrackerClient trackerClient = new TrackerClient();
            //2:连接TrackerServer端
            TrackerServer trackerServer = null;
            trackerServer = trackerClient.getConnection();
            //3:创建Storage的客户端
            StorageServer storageServer = null;
            StorageClient1 storageClient1 = new StorageClient1(trackerServer,storageServer);
            //4:上传文件   meta : 元数据信息  作者  什么时候 多大 有意思吗？

            //  5f7eafcd01dd2304.jpg
            String ext = FilenameUtils.getExtension(file.getOriginalFilename());

            String fileId = storageClient1.upload_file1(
                    file.getBytes()
                    , ext, null);
            //    http://192.168.200.136:8080/group1/M00/00/00/wKjIgWCXj76AAKhQAAT8_AoEzOU949.jpg
            System.out.println(imageUrl + fileId);
            return Result.ok(imageUrl + fileId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
